package com.lbs.jiepiaisi.base;

import android.util.Log;

import com.google.gson.JsonParseException;
import com.lbs.jiepiaisi.utils.ToastUtil;

import org.json.JSONException;

import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.net.UnknownServiceException;
import java.text.ParseException;

import retrofit2.HttpException;

/**
 * Created by yu on 2019-12-18 10:25.
 * Description:
 */

public class RxExceptionUtil {
	public static ErrorException exceptionHandler(Throwable e){
		ErrorException error = new ErrorException();
		error.setMsg("未知异常");
		error.setCode(-1);
		error.setE(e);
		if (e instanceof UnknownHostException) {
			error.setMsg("网络已断开,请检查网络设置");
			ToastUtil.show("网络已断开,请检查网络设置");
		} else if (e instanceof SocketTimeoutException) {
			error.setMsg("网络不给力,请稍后再试");
			ToastUtil.show("网络不给力,请稍后再试");
		} else if (e instanceof UnknownServiceException) {
			error.setMsg("服务器异常");
			ToastUtil.show("服务器异常");
		} else if (e instanceof SocketException) {
			error.setMsg("服务器异常");
			ToastUtil.show("服务器异常");
		} else if (e instanceof HttpException) {
			HttpException httpException = (HttpException)e;
			error.setMsg(convertStatusCode(httpException));
			ToastUtil.show(convertStatusCode(httpException));
		} else if (e instanceof JsonParseException || e instanceof JSONException || e instanceof ParseException) {
			error.setMsg("数据解析异常");
			ToastUtil.show("数据解析异常");
		} else if (e instanceof ResultException) {
			ResultException resultException = (ResultException)e;
			error.setMsg(resultException.getMsg());
			error.setCode(resultException.getCode());
		}
		Log.e("error",""+error.toString());
		return error;
	}

	private static String convertStatusCode(HttpException httpException) {
		String msg;
		if (httpException.code() >= 500 && httpException.code() < 600) {
			msg = "服务器处理请求出错";
		} else if (httpException.code() >= 400 && httpException.code() < 500) {
			msg = "服务器无法处理请求";
		} else if (httpException.code() >= 300 && httpException.code() < 400) {
			msg = "请求被重定向到其他页面";
		} else {
			msg = httpException.message();
		}
		return msg;
	}
}
